package jp.co.cos.ittrick.channel.controller.client;

import java.util.List;

import jp.co.cos.ittrick.channel.model.CategoryModel;
import jp.co.cos.ittrick.channel.model.ChannelModel;
import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.service.CategoryService;
import jp.co.cos.ittrick.channel.service.ChannelService;
import jp.co.cos.ittrick.channel.service.ChapterService;
import jp.co.cos.ittrick.channel.service.PageService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

public class DeleteChannelController extends Controller {

    private ChannelService channelService;
    private CategoryService categoryService;
    private ChapterService chapterService;
    private PageService pageService;

    public DeleteChannelController() {
        channelService = new ChannelService();
        categoryService = new CategoryService();
        chapterService = new ChapterService();
        pageService = new PageService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String channel = asString("channel");

        ChannelModel channelModel = channelService.getChannelByKey(channel);
        List<CategoryModel> categoryList = channelModel.getCategoryModelListRef().getModelList();

        for(CategoryModel categoryModel: categoryList) {

            List<ChapterModel> chapterList = categoryModel.getChapterModelListRef().getModelList();
            for(ChapterModel chapterModel: chapterList) {

                List<PageModel> pageList = chapterModel.getPageModelListRef().getModelList();
                for(PageModel pageModel: pageList) {
                    // Page の削除
                    pageService.delete((int)pageModel.getKeyString());
                }

                // Chapter の削除
                chapterService.delete((int)chapterModel.getKeyString());
            }

            // Category の削除
            categoryService.delete((int)categoryModel.getKeyString());
        }

        channelService.delete(channel);

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.getWriter().println("0");
        response.flushBuffer();

        return null;
    }
}
